package tpaagp.scheduleus;

import com.ibm.mqtt.MqttClient;
import com.ibm.mqtt.MqttException;
import com.ibm.mqtt.MqttSimpleCallback;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;


public class ScheduleUsActivity extends Activity {
	/** Called when the activity is first created. */
	private String android_id;
	private MqttClient client;

	final static String broker = "tcp://87.219.168.155:1883";
	// Constant definitions
	private static final int ACTIVITY_CREATE = 0;
	protected static final int NOTIF_ALERTA_ID = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		ImageView logo = (ImageView) findViewById(R.id.startLogo);
		
		logo.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				// First, check if this is the first time the application is
				// started and, if not, create the preferences file.
				SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
				boolean firstTime = prefs.getBoolean("firstTime", true);
				boolean availabilitySet = prefs.getBoolean("availability", false);

				if (firstTime) {
					// Call the firstTime activity
					firstTime();
				}
				else if(!availabilitySet) {
					//Now we have to check that the availability has been set
					connect();
					alertNoAbaliability();
				}
				else {
					connect();
					optionsMenu();
				}
				
			}
		});
		
	}

	public void firstTime() {
		Intent i = new Intent(this, FirstTime.class);
		startActivityForResult(i, ACTIVITY_CREATE);
	}

	
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		alertNoAbaliability();
	}
	
	
	private void alertNoAbaliability() {
		AlertDialog.Builder a = new AlertDialog.Builder(this);
		a.setMessage(R.string.remember).setPositiveButton("OK",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						optionsMenu();
					}
				});
		a.show();
	}
	
	
	private void optionsMenu() {
		Intent i = new Intent(this, OptionsMenu.class);
		try {
			startActivity(i);
		} catch(ActivityNotFoundException e) {
			System.out.println("Activity not found");
		}
	}
	
	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			//Get a reference of the notifications service
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
			boolean notificationsEnabled = prefs.getBoolean("notificationsEnabled", true);
			if (notificationsEnabled) { 
				String ns = Context.NOTIFICATION_SERVICE;
				NotificationManager notManager =
				    (NotificationManager) getSystemService(ns);
				int icono = R.drawable.icon;
				CharSequence textoEstado = "Schedule Us";
				long hora = System.currentTimeMillis();
				 
				Notification notif =
				    new Notification(icono, textoEstado, hora);
				//Make Intent
				Context contexto = getApplicationContext();
				CharSequence titulo = "Nuevo meeting";
				CharSequence descripcion = msg.getData().getString("message");
				prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
				SharedPreferences.Editor ed = prefs.edit();
				ed.putString("name_meeting",(String) descripcion);
				ed.commit();
				Intent notIntent = new Intent(contexto,
				    AcceptMeetActivity.class);
				 
				PendingIntent contIntent = PendingIntent.getActivity(
				    contexto, 0, notIntent, 0);
				 
				notif.setLatestEventInfo(
				    contexto, titulo, descripcion, contIntent);
				//AutoCancel: cuando se pulsa la notificai�n �sta desaparece
				notif.flags |= Notification.FLAG_AUTO_CANCEL;
				 
				//Add sound, vibrate and lights
				//notif.defaults |= Notification.DEFAULT_SOUND;
				//notif.defaults |= Notification.DEFAULT_VIBRATE;
				//notif.defaults |= Notification.DEFAULT_LIGHTS;
				//Send notification
				notManager.notify(NOTIF_ALERTA_ID, notif);
			}			
		}
	};

	public boolean connect() {
		try {
			client = (MqttClient) MqttClient.createMqttClient(broker, null);
			client.registerSimpleHandler(new MessageHandler());
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
			String user_id = prefs.getString("Name", "defValue");
			client.connect("HM" + user_id, true, (short) 240);
			String topics[] = { "sensors/temperature" };
			int qos[] = { 1 };
			client.subscribe(topics, qos);
			return true;
		} catch (MqttException e) {
			e.printStackTrace();
			return false;
		}
	}

	@SuppressWarnings("unused")
	private class MessageHandler implements MqttSimpleCallback {
		public void publishArrived(String _topic, byte[] payload, int qos, boolean retained) throws Exception {
			String _message = new String(payload);
			Bundle b = new Bundle();
			b.putString("topic", _topic);
			b.putString("message", _message);
			Message msg = handler.obtainMessage();
			msg.setData(b);
			handler.sendMessage(msg);
			Log.d("MQTT", _message);

		}

		public void connectionLost() throws Exception {
			client = null;
			Log.v("HelloMQTT", "connection dropped");
			Thread t = new Thread(new Runnable() {

				public void run() {
					do {// pause for 5 seconds and try again;
						Log.v("HelloMQTT", "sleeping for 10 seconds before trying to reconnect");
						try {
							Thread.sleep(10 * 1000);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					} while (!connect());
					System.err.println("reconnected");
				}
			});
		}
	}
	
	
}